<template>
    <section class="oragin_info_form" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" size="small" style="width: 380px;" v-if="type==='add'" ></el-input>
                <el-input v-model="form.name" size="small" style="width: 380px;" v-if="type==='update'"></el-input>
                <span v-if="type==='detail'">{{this.form.name}}</span>
            </el-form-item>
            <el-form-item label="资源标识">
                <el-input  style="width: 180px;" size="small" placeholder="由系统自动生成" disabled v-if="type==='add'"></el-input>
                <el-input  style="width: 180px;" size="small" v-model="form.flowNum" disabled v-if="type==='update'"></el-input>
                <span v-if="type==='detail'">{{this.form.flowNum}}</span>
            </el-form-item>

            <el-form-item label="状态">
                <el-radio-group v-model="form.radioState" size="small" v-if="type==='add'">
                    <el-radio-button :label="1" >启用</el-radio-button>
                    <el-radio-button :label="0" >禁用</el-radio-button>
                </el-radio-group>
            <el-radio-group v-model="form.radioState" size="small" v-if="type==='update'" >
                <el-radio-button :label="1" >启用</el-radio-button>
                <el-radio-button :label="0" >禁用</el-radio-button>
            </el-radio-group>
                <span v-if="type==='detail'">{{this.form.state ? '启用' : '禁用'}}</span>
            </el-form-item>

            <el-form-item label="联系人" prop="contacts">
                <el-input v-model="form.contacts" size="small" style="width: 380px;" v-if="type==='add'" ></el-input>
                <el-input v-model="form.contacts" size="small" style="width: 380px;" v-if="type==='update'"></el-input>
                 <span v-if="type==='detail'">{{this.form.contacts}}</span>
            </el-form-item>
            <el-form-item label="联系电话" prop="contactsTel">
                <el-input v-model="form.contactsTel" size="small" style="width: 380px;" v-if="type==='add'" ></el-input>
                <el-input v-model="form.contactsTel" size="small" style="width: 380px;" v-if="type==='update'"></el-input>
                 <span v-if="type==='detail'">{{this.form.contactsTel}}</span>
            </el-form-item>

           <el-form-item label="所属部门" v-if="type==='detail'">
               <span>{{this.form.organizationName}}</span>
           </el-form-item>

           <el-form-item label="所属区域" v-if="type==='detail'">
               <span>{{this.form.checkListQuyu}}</span>
           </el-form-item>

            <el-form-item label="所属部门" required v-if="type==='add' || type==='update'">
                <el-select v-model="form.organizationId">
                    <el-option
                        v-for="item in parentOptions"
                        :key="item.orgId"
                        :label="item.name"
                        :value="item.orgId"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
              <el-form-item label="所属区域" required v-if="type==='add' || type==='update'">
                <el-select v-model="form.checkListQuyu">
                    <el-option
                        v-for="item in checkListQuyuList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="类型" v-if="type==='add'">
                <el-radio-group v-model="addRadio" :min="1" >
                    <el-radio @change="change2(1)" :label="1" name="type"  style="display: block;">请求方</el-radio>

                    <div style="margin-top: 20px">
                        <el-form-item label-width="100px"
                            v-if="quyuDisplay"
                            v-model="form.input1"
                            size = "small"
                            :label="'请求IP地址'+(Number(index)+1)"
                            v-for="(item,index) in form.input1"
                            :prop="'input1.' + index + '.adress'"
                            :rules="[
                                {
                                    required: true, message: 'IP地址不能为空', trigger: 'blur'
                                },
                                {
                                    pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/, message: '请输入有效的IP地址' 
                                }
                            ]"
                            style="margin-bottom: 20px;"
                        >
                            <el-input v-model="item.adress" style="width: 280px;"></el-input>
                            <i @click="addIp" class="el-icon-circle-plus-outline" v-if="index===form.input1.length-1"></i>
                            <i @click="delIp(index)" class="el-icon-circle-close-outline" 
                                v-if="index!=form.input1.length-1">
                            </i>
                        </el-form-item>
                    </div>
                    <el-radio @change="change2(0)" :label="0" name="type" style="display: block;">服务方</el-radio>
                    
                </el-radio-group>
            </el-form-item>
            <el-form-item label="类型" v-if="type==='update' && form.type==='请求方'">
              <el-checkbox-group v-model="form.checkList" :min="1" >
                    <el-checkbox :label="1" name="type"  style="display: block;" disabled>请求方</el-checkbox>
                    
                    <div style="margin-top: 20px">
                        <el-form-item label-width="100px"
                            v-if="quyuDisplay"
                            v-model="form.input1"
                            size = "small"
                            :label="'请求IP地址'+(Number(index)+1)"
                            v-for="(item,index) in form.input1"
                            :prop="'input1.' + index + '.adress'"
                            :rules="[
                                {
                                    required: true, message: 'IP地址不能为空', trigger: 'blur'
                                },
                                {
                                    pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/, message: '请输入有效的IP地址' 
                                }
                            ]"
                            style="margin-bottom: 20px;"
                        >
                            <el-input v-model="item.adress" style="width: 280px;"></el-input>
                            <i @click="addIp" class="el-icon-circle-plus-outline" v-if="index===form.input1.length-1"></i>
                            <i @click="delIp(index)" class="el-icon-circle-close-outline" 
                                v-if="index!=form.input1.length-1">
                            </i>
                        </el-form-item>
                    </div>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item  label="类型" v-if="type==='detail'">
                <span >{{this.form.type===0?"服务方":"请求方"}}</span>
            </el-form-item>
      <div class="fixed_button">      
          <el-form-item v-if="type==='add'">
            <el-button @click="disappears">取消</el-button>
            <el-button type="primary" @click="onSubmit('form')">确定</el-button>
          </el-form-item>
          <el-form-item v-if="type==='update'">
            <el-button @click="disappears">取消</el-button>
            <el-button type="primary" @click="onSubmitUpdata('form')">确定</el-button>
          </el-form-item>
          <el-form-item v-if="type==='detail'">
            <el-button type="primary" @click="disappears">关闭</el-button>
          </el-form-item>
      </div>
    </el-form>
    </section>
</template>

<script>
    import {organizationDataExchangeListDetail,
            organizationDataExchangeAdd,
            organizationDataExchangeUpdata,
            organizationDataExchangeListSearch,
            organizationDataExchangeQuyu,
            organizationList,
    } from '../../api/data-exchange-api.js'
	import {computedCheckName} from '../../serverResource/common/js_css_img/serverResourceComputed'
    export default {
        props:{
            type: {     //显示add,update,detail的值
                type: String,
                default: 'auto'
            },
            objDetail: Object,  //具体对象详细内容
            content: '',
            objid: {
                type: Number,
                default: '',
            },
            organization: Object
        },
        data() {
        	var checkName = (rule,value,callback)=>{
	          	if (!value) {
		          return callback(new Error('名字不能为空'));
		        }
	          	computedCheckName(this,value,this.objid,'zuzhi');
	          	setTimeout(()=>{
		          if(this.has){
		            return callback(new Error('名称已存在，请重新输入'));
		          }else {
		            callback();  //必须要有回调，要不然表单无法提交
		          }
		      },1500)
          	};
            return {
            	has:false,
                form: {
                    name: '',   //组织名称
                    code: '',   //编码
                    flowNum:'',
                    type: 1,   //详情类型
                    state: '',    //详情状态
                    radioState:'1',    //状态
                    checkList:[1,],   //请求方，服务方选择
                    checkListQuyu: '',    //所属区域
                    input1:[
                        {
                          adress:''    //请求方IP地址
                        }
                    ],
                    organizationId: Number,
                    contactsTel:'',
                    contacts: '',
                    organizationName:'',
                },
                rules: {
                    name:[
                    	{ validator: checkName, trigger: 'blur' },
                        { required: true, message: '请输入组织信息名称', trigger: 'blur' },
                        { min: 3, max: 20, message: '长度在 3 到 20个字符', trigger: 'blur' }
                    ],
                    checkListQuyu: [
                        {  required: true, message: '请至少选择一个区域', trigger: 'change' }
                    ],
                    contacts:[
                        { required: true, message: '请输入联系人', trigger: 'blur' },
                        { min: 1, max: 20, message: '长度在 1 到 20个字符', trigger: 'blur' }
                    ],
                    contactsTel:[
                        { required: true, message: '请输入联系电话', trigger: 'blur' },
                        { min: 6, max: 11, message: '长度在6- 11个数字', trigger: 'blur' }
                    ],
                },
                ips: '',    //添加的IP地址
                contacts: '',    //添加的联系方式
                checkListQuyuList: [],    //查询所属区域列表
                selectcheckListQuyu: '',    //选择打钗的区域
                quyuDisplay: true,  //是否显示选择区域
                producerTypeSelectDispaly: false,   //是否显示填写联系人
                requesterType: '',  //选择请求方
                producerType: '',   //选择服务方
                parentOptions:[],
                addRadio: 1,
            }
        },
        methods: {
            onSubmit(formName) {    //提交新增组织
            	if(this.has){
            		this.$message.error('名称已经存在')
            		return false;
            	}
                this.countIps();
               // this.countContacts();
                this.$refs[formName].validate((valid) => {
                  if (valid) {
                    organizationDataExchangeAdd({   //新增组织信息
                        requesterType: this.requesterType,   //请求方固定了值是1，如果它是请求方就写1，如果不是请求方传空值
                        nodeIds:  this.selectcheckListQuyu, //'90，9，'     //区域选择
                        name: this.form.name,       
                        producerType: this.producerType ,    //服务方，固定了值是1，如果它是服务方就写1，如果不是服务方传空值
                        status: this.form.radioState ,      //状态
                        ips: this.ips ,
                        contacts: this.form.contacts, 
                        contactsTel:this.form.contactsTel,
                        organizationId:this.form.organizationId,
                        type:this.form.type
                        }).then(res => {
                            if( res.data.code == 'S100101'){
                                //清空输入框数据
                                this.clearEntry();
                                this.$message.success('成功新增组织信息')
                                this.$emit('fatherListSearch'); 
                                this.disappears();
                            }else{
                                this.$message.error(res.data.msg)
                            }
                        }).catch(error =>{
                            console.log(error);
                    });
                  } else {
                    this.$message.error('请填写正确的数据')
                    return false;
                  }
                });
                
            },
            change2(val){
             console.log("val");
             if(val=='1'){
                this.quyuDisplay = true;
                this.requesterType=1;
                this.producerType='';
             }else{
                 this.quyuDisplay = false;
                  this.requesterType='';
                this.producerType=1;
             }
             
            },
            onSubmitUpdata(formName){     //组织信息更新
            	if(this.has){
            		this.$message.error('名称已经存在')
            		return false;
            	}
                this.countIps();
               // this.countContacts();
                this.$refs[formName].validate((valid) => {
                  if (valid) {
                        organizationDataExchangeUpdata({
                            id: this.objid,    //必须要传id
                            requesterType: this.requesterType,   //请求方
                            producerType: this.producerType,    //服务方
                            nodeIds:  this.selectcheckListQuyu ,      //'90，9，'     //区域选择
                            name: this.form.name,
                            status: this.form.radioState,   //状态
                            ips: this.ips,
                            contacts: this.form.contacts, 
                            contactsTel:this.form.contactsTel,
                            organizationId:this.form.organizationId,
                            // type:this.form.type
                        }).then(res => {
                            if( res.data.code == 'S100101'){
                                this.disappears();
                                //清空输入框数据
                                this.clearEntry();
                                this.$message.success('组织信息更新成功!')
                                this.$emit('fatherListSearch');  
                            }else{
                                this.$message.error(res.data.msg)
                            }
                        }).catch(error =>{
                            console.log(error);
                        })
                  } else {
                    this.$message.error('请填写正确的数据')
                    return false;
                  }
                });
                
            },
            listSearch(){   
                organizationDataExchangeListSearch(this.organization).then(res => {
                    const result = res.data.data.list;
                    console.log(res.data.data);
                    const tableData = [];
                    for(let i=0 ; i < result.length; i++ ){
                        let obj = {};
                        let resultType = '';
                        let resultState = '';
                        if(result[i].producerType == 1 && result[i].requesterType == 1){
                            resultType = '服务方/请求方'
                        }else if(result[i].requesterType == 1){
                            resultType = '请求方'
                        }else if(result[i].producerType == 1){
                            resultType = '服务方'
                        }
                        resultState = result[i].status ? '启用' : '禁用';
                        obj.code = result[i].id;
                       obj.flowNum = result[i].flowNum;
                        obj.oragion = result[i].name;
                        obj.type = resultType;
                        obj.state = resultState;
                        tableData.push(obj);
                        // console.log(obj);
                        this.$emit('tableDataSub',tableData)
                    }
                }).catch(error => {
                    console.log(error);
                })
            },
            addIp(){/*请求IP地址增加*/
                this.form.input1.push({address:''});
                console.log(this.form.input1);
            },
            addPhone(){    //添加服务方联系方式
                this.form.input2.push({name:'',phone:''});
            },
            delPhone(index){
                this.form.input2.splice(index,1);
            },
            delIp(index){
                this.form.input1.splice(index,1);
            },
            disappears(){
                this.$emit('disappear', false);
            },
            listDetail(param){
                organizationDataExchangeListDetail({},param).then( res => {   //组织信息列表详细内容
                    const forms = res.data.data
                    console.log(forms);
                    this.form.name = forms.name
                    this.form.code = forms.id
                    this.form.flowNum = forms.flowNum
                    this.form.contactsTel = forms.contactsTel
                    this.form.contacts = forms.contacts
                    this.form.organizationId = Number(forms.organizationId)
                    this.form.type = forms.type;
                    this.form.state = forms.status
                    this.form.radioState = forms.status===2?1:forms.status  //更新时显示的状态
                    this.form.checkListQuyu = forms.nodeIds;
                    this.form.organizationName = forms.organizationName;
                    setTimeout(() => {
                        this.checkListQuyuList.map(res=>{   //回显中文
                            if(this.form.checkListQuyu === res.id){
                                this.form.checkListQuyu = res.name;
                                console.log(res.name);
                            }
                        });
                    }, 150);
                    
                    let ipss = forms.ips.split(',');
                    this.form.input1 = [];
                    for(let i=0; i<ipss.length; i++){
                        this.form.input1.push({adress:ipss[i]});
                    }
                    let contactss = forms.contacts.split(';');
                    this.form.input2 = [];
                    for(let i=0; i<contactss.length-1; i++){
                        this.form.input2.push({name:contactss[i].split(',')[0],phone:contactss[i].split(',')[1]});
                    }
                }).catch(error => {
                    console.log(error)
                });
            },
            listSearchQuyu(){   //查询区域数据
                organizationDataExchangeQuyu({}).then(res =>{
                    this.checkListQuyuList = res.data.data.list;
                    // console.log(res); 
                }).catch(error =>{
                    console.log(error);
                });
            },
            listOrg(){   //查询耳机部门列表
                organizationList({"parentIds":[0,1]}).then(res =>{
                    this.parentOptions = res.data.data.list;
                    
                    console.log("res数据。。。。"); console.log(this.parentOptions); 
                }).catch(error =>{
                    console.log(error);
                });
            },
            formTypeChange(){   //类型更新
                    if(this.requesterType == 1 && this.producerType==1){
                        this.form.type = '服务方/请求方'
                    }else if(this.requesterType == 1){
                        this.form.type = '请求方'
                    }else if(this.producerType==1){
                        this.form.type = '服务方'
                    }
            },
            countIps(){   //计算ips的值
                let result;
                let newAddress = this.form.input1;
                for(let i = 0; i < newAddress.length; i++){
                    if(newAddress[i].adress != undefined){
                        result += newAddress[i].adress+','
                        let end = result.slice(9);
                        this.ips = end;
                        console.log(this.ips);
                    }
                }
            },
            countContacts(){    //计算contacts的值
                let result;
                let newName = this.form.input2
                for(let i = 0; i < newName.length; i++){
                    result += newName[i].name + ',' + newName[i].phone +';'
                    let end = result.slice(9);
                    this.contacts = end;
                    console.log(this.contacts);
                }
            },
            clearEntry(){   //清空输入框数据
                this.form = {
                    name: '',   //组织名称
                    code: '',   //编码
                    type: '',   //详情类型
                    state: '',    //详情状态
                    radioState:"1",    //状态
                    checkList:[1,],   //请求方，服务方选择
                    checkListQuyu: '',    //所属区域
                    input1:[
                        {
                          adress:''    //请求方IP地址
                        }
                    ],
                    input2:[
                        {
                          name:'',    //联系人名称
                          phone:'',    //联系人手机
                        }
                    ],
                };
            }
        },
        watch: {
            objid: function(newval,oldval) {
                //解决详细内容第一次不更新问题
                alert(objid);
                if(newval == 0){
                    this.listDetail(oldval);
                    this.formTypeChange();
                }else{
                    this.listDetail(newval);
                    this.formTypeChange();
                }
            },
            type: function(newVal,oldval){    //新增组织时，名称输入框里清空
                if(newVal== 'add'){
                    //清空输入框数据
                    this.clearEntry();
                    console.log('新增组织时，名称输入框里清空new')
                }else if( newVal == 'update'){
                    console.log('++++++999')
                    this.listDetail(this.objid);
                }
            },
            'form.checkListQuyu': { //选择区域方法
                handler(newval, oldval){
                    console.log(newval.toString());
                    this.selectcheckListQuyu = newval.toString();
                },
                immediate: true,
            },
            'form.checkList': {
                handler(newName, oldName) {     //请求方与服务方的选择处理
                    console.log('长度'+newName.length+'--请求方与服务方--'+'个数'+newName)
                    if( newName.length == 1){
                        if(newName[1] == 1 || newName[0] == 1){
                            this.requesterType = 1;
                            this.producerType = ''
                            console.log('选择了请求方')
                        }else{
                            this.requesterType = '';
                            this.producerType = 1
                            console.log('选择了服务方')
                        }
                    }else{
                        this.requesterType = 1;
                        this.producerType = 1;
                        console.log('---请求方和服务方都被选择了------');
                    }

                    if(this.requesterType == ''){
                        this.quyuDisplay = false;   //不显示区域选择
                        this.form.checkListQuyu = '';   //清空所有选择区域
                        this.selectcheckListQuyu = '';
                        this.form.input1 = [{adress:''}];
                    }else{
                        // this.quyuDisplay = true;
                    }

                    if(this.producerType == ''){
                        this.producerTypeSelectDispaly = false;   //不显示填写联系人
                        this.form.input2 = [{name:'',phone:''}];
                        this.contacts = '';
                    }else{
                        this.producerTypeSelectDispaly = true;
                    }
                    console.log('------------分隔线----------');
                    console.log(this.requesterType+'请求方');
                    console.log(this.producerType+'服务方');

                },
                immediate: true,
            },
            'form.input2': {
                handler(newName, oldName){
                    //计算contacts的值
                    console.log(newName);
                    let result;
                    for(let i = 0; i < newName.length; i++){
                        result += newName[i].name + ',' + newName[i].phone +';'
                        let end = result.slice(9);
                        this.contacts = end;
                        console.log(end)
                    }
                }
            }
        },
        computed: {
            
        },
        mounted(){
            console.log(this.type);
            console.log('99999f')
            if(this.type != "add"){
                this.listDetail(this.objid);
            }
        },
        created(){
            // this.objid = 0;    //解决详细内容第一次不更新问题
            this.listSearchQuyu();  //查询并显示区域
            this.listOrg();
            if(this.type=='add'){
                //清空输入框数据
                this.clearEntry();
                console.log('add++')
            }else{
                this.listDetail(this.objid);
            }
            
            console.log(this.type);
        }
    }
</script>

<style scoped>
    .oragin_info_form .title{
      font-size: 20px;
      margin-bottom: 10px;
    }
    .oragin_info_form .el-checkbox+.el-checkbox{
      margin-left: unset;
    }
    .oragin_info_form .el-icon-circle-plus-outline,.oragin_info_form .el-icon-circle-close-outline{
      font-size: 24px;
      vertical-align: middle;
      margin-left: 10px;
      color: #b3d3fb;
    }
    .fixed_button{
        position: fixed;
        bottom: 0px;
        margin-left: -20px;
        background: #e0eefd80;
        width: 50%;
        height: 60px;
        line-height: 60px;
        text-align: center;
    }
    .fixed_button .el-form-item{
            margin-top:10px;    
    }
    .el-dialog__header{
        border-bottom: 1px solid #ccc;
    }
</style>
